package cn.lyq.card.ui.store

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.ListInfo
import cn.lyq.card.data.model.PageInfo
import cn.lyq.card.data.model.StoreInfo
import cn.lyq.card.data.src.Result
import cn.lyq.card.data.src.Status
import cn.lyq.card.utils.getVisibility
import cn.lyq.card.utils.setClick
import cn.lyq.card.utils.setOnTabSelected
import cn.lyq.card.utils.setSimpleData
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_store_list.*
import kotlinx.android.synthetic.main.layout_tab_normal.*

class StoreListActivity : BaseActivity() {


    private val type by lazy {
        intent.getIntExtra(KEY_TYPE, 0)
    }
    private val date by lazy {
        intent.getStringExtra(KEY_DATE) ?: ""
    }
    private val mModel by lazy {
        getVM(StoreVM::class.java)
    }
    private val mAdapter by lazy {
        StoreAdapter()
    }
    private var key = ""
    private var storeType = 0
    private val page = PageInfo()

    companion object {

        private const val KEY_TYPE = "TYPE"
        private const val KEY_DATE = "DATE"

        /**
         * 0日、1月、2全部
         */
        @JvmStatic
        fun start(context: Context, type: Int, date: String) {
            val starter = Intent(context, StoreListActivity::class.java)
                .putExtra(KEY_TYPE, type)
                .putExtra(KEY_DATE, date)
            context.startActivity(starter)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_store_list
    }

    override fun initView() {
        super.initView()
        setMyTitle(if (type == 2) R.string.str_store_amount else R.string.str_store_new)
        tvSearchSplit.visibility = getVisibility(type != 2)
        tabLayout.visibility = getVisibility(type != 2)
        tabLayout.setSimpleData(arrayOf("全部", "优质商户", "活跃商户", "休眠商户"))
        tabLayout.setOnTabSelected {
            tvStoreTip.setText(
                when (it) {
                    1 -> R.string.str_good_store_desc
                    2 -> R.string.str_active_store_desc
                    3 -> R.string.str_sleep_store_desc
                    else -> R.string.str_good_store_desc
                }
            )
            storeType = it
            tvSearchSplit.visibility = getVisibility(it != 0)
            groupSearch.visibility = getVisibility(it != 0)
            tvStoreTip.visibility = getVisibility(it == 0)
            key = if (it == 0) {
                etSearch.text.toString().trim()
            } else {
                ""
            }
            getData(page.refresh())
        }

        rv.layoutManager = LinearLayoutManager(this)
        rv.adapter = mAdapter
        mAdapter.setEmptyView(R.layout.layout_empty)
        mAdapter.loadMoreModule.apply {
            checkDisableLoadMoreIfNotFullPage()
            preLoadNumber = 2
            setOnLoadMoreListener {
                getData(page.loadMore())
            }
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            StoreDetailActivity.start(this, mAdapter.data[position])
        }
    }

    private fun getData(pageNum: Int) {
        mModel.getData(pageNum, key, date, storeType).observe(this, Observer {
            when (it?.status) {
                Status.SUCCESS -> {
                    loadSuccess(it)
                }
                Status.ERROR -> {
                    page.fail()
                    refreshLayout.isRefreshing = false
                    mAdapter.loadMoreModule.loadMoreFail()
                    ToastUtils.showShort(it.message.getMsg())
                }
                Status.LOADING -> {
                    if (page.isRefresh() && !refreshLayout.isRefreshing) {
                        refreshLayout.isRefreshing = true
                    }
                }
            }
        })
    }

    private fun loadSuccess(it: Result<ListInfo<StoreInfo>>) {
        val temp = it.requireData().list
        page.total = it.requireData().count
        if (page.isRefresh()) {
            mAdapter.key = key
            mAdapter.setList(temp)
            rv.scrollToPosition(0)
        } else {
            mAdapter.addData(temp)
        }
        page.success()
        if (page.hasMore()) {
            mAdapter.loadMoreModule.loadMoreComplete()
        } else {
            mAdapter.loadMoreModule.loadMoreEnd()
        }
        refreshLayout.isRefreshing = false
    }

    override fun initListener() {
        super.initListener()
        refreshLayout.setOnRefreshListener {
            key = etSearch.text.toString()
            getData(page.refresh())
        }
        tvSearch.setClick {
            key = etSearch.text.toString()
            KeyboardUtils.hideSoftInput(etSearch)
            getData(page.refresh())
        }
    }

    override fun initObserver() {
        super.initObserver()
        mModel.type = type
        getData(page.refresh())
    }
}